package cn.iocoder.yudao.module.system.controller.admin.ai;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.idempotent.core.annotation.*;
import cn.iocoder.yudao.framework.idempotent.core.keyresolver.impl.*;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.UserReportPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.UserReportRespVO;
import cn.iocoder.yudao.module.system.controller.admin.ai.vo.UserReportSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.answerRecord.vo.AnswerRecordSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.ai.UserReportDO;
import cn.iocoder.yudao.module.system.dal.dataobject.answerRecord.AnswerRecordDO;
import cn.iocoder.yudao.module.system.service.ai.UserReportService;
import cn.iocoder.yudao.module.system.service.answerRecord.AnswerRecordService;
import cn.iocoder.yudao.module.system.util.baidu.BaiduAiUtils;
import cn.iocoder.yudao.module.system.util.baidu.TextFomatterUtils;
import cn.iocoder.yudao.module.system.mq.producer.ReportProducer;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.system.util.baidu.BaiduAiUtils.APP_BUILDER_TOKEN;

/**
 * @author zhaoying
 */
@RestController
@RequestMapping("/system/report")
public class ReportController {

    private static final Logger log = LoggerFactory.getLogger(ReportController.class);

    @Resource
    private UserReportService userReportService;

    @Resource
    private AnswerRecordService answerRecordService;

    @Resource
    private ReportProducer reportProducer;



    /**
     * @Param question 问题
     * @Param version 版本 0-基础版 1-专业版
     *
     */

    @PostMapping("/generate")
    @PermitAll
    @Idempotent(timeout = 60, timeUnit = java.util.concurrent.TimeUnit.SECONDS,
              keyResolver = ExpressionIdempotentKeyResolver.class,
              keyArg = "#userReportSaveReqVO.userId + ':' + #userReportSaveReqVO.answerRecordId",
              message = "报告正在生成中，请勿重复提交")
    public CommonResult<Boolean> generateReport(@RequestBody UserReportSaveReqVO userReportSaveReqVO) {
        log.info("[generateReport][开始处理报告生成请求: userId={}, answerRecordId={}, version={}]",
                userReportSaveReqVO.getUserId(), userReportSaveReqVO.getAnswerRecordId(), userReportSaveReqVO.getVersion());

        //question 为{"1":{"questionContent":"学生所处的高考省份","answer":"辽宁"},"2":{"questionContent":"学生性别","answer":"我是女生"},"3":{"questionContent":"学生选科","answer":["历史","生物","政治"]},"5":{"questionContent":"高考总分","answer":"538"},"6":{"questionContent":"各科分数","answer":"语文:88,数学:99,英语:88,历史:99,生物:99,政治:65"},"7":{"questionContent":"意向专业","answer":["护理学"]},"8":{"questionContent":"性格","answer":"内向"},"9":{"questionContent":"学习能力","answer":"强"},"10":{"questionContent":"社交能力","answer":"弱"},"11":{"questionContent":"家庭年收入（单位元）","answer":"10万到20万"},"12":{"questionContent":"就业方向","answer":"体制内"},"13":{"questionContent":"人脉资源","answer":""},"14":{"questionContent":"毕业去向","answer":"就业"},"15":{"questionContent":"就读城市省份","answer":"全国"}}
        try {
            // 从question中提取意向专业的answer并设置为name
            if (userReportSaveReqVO.getQuestion() != null && !userReportSaveReqVO.getQuestion().isEmpty()) {
                try {
                    // 解析question JSON
                    JSONObject questionJson = JSONUtil.parseObj(userReportSaveReqVO.getQuestion());
                    // 寻找意向专业的answer作为name
                    if (!questionJson.isEmpty()) {
                        for (String key : questionJson.keySet()) {
                            JSONObject questionObj = questionJson.getJSONObject(key);
                            if (questionObj != null && questionObj.containsKey("questionContent") &&
                                "意向专业".equals(questionObj.getStr("questionContent"))) {

                                // 获取意向专业的answer
                                if (questionObj.containsKey("answer")) {
                                    Object answerObj = questionObj.get("answer");
                                    String name = "";

                                    // answer可能是数组或字符串
                                    if (answerObj instanceof JSONObject) {
                                        name = answerObj.toString();
                                    } else if (answerObj instanceof java.util.List) {
                                        java.util.List<?> answerList = (java.util.List<?>) answerObj;
                                        if (!answerList.isEmpty()) {
                                            name = answerList.get(0).toString();
                                        }
                                    } else {
                                        name = answerObj.toString();
                                    }

                                    if (!name.isEmpty()) {
                                        userReportSaveReqVO.setName(name);
                                        log.info("[generateReport][设置报告名称: name={}]", name);
                                    }
                                    break; // 找到意向专业的answer后退出循环
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.warn("[generateReport][解析question获取意向专业的answer失败]", e);
                }
            }

            // 立即更新AnswerRecord的reportName和question字段
            if (userReportSaveReqVO.getAnswerRecordId() != null) {
                try {
                    // 获取当前的AnswerRecord
                    AnswerRecordDO answerRecord = answerRecordService.getAnswerRecord(userReportSaveReqVO.getAnswerRecordId());
                    if (answerRecord != null) {
                        // 创建更新请求对象
                        AnswerRecordSaveReqVO updateReqVO = new AnswerRecordSaveReqVO();
                        updateReqVO.setId(answerRecord.getId());
                        updateReqVO.setUserId(answerRecord.getUserId());
                        updateReqVO.setLastAnswerQuestionId(answerRecord.getLastAnswerQuestionId());
                        updateReqVO.setAnswerNo(answerRecord.getAnswerNo());
                        updateReqVO.setStatus(2);
                        updateReqVO.setType(answerRecord.getType());
                        updateReqVO.setReportCount(answerRecord.getReportCount());
                        updateReqVO.setRecommend(answerRecord.getRecommend());

                        // 设置报告名称（如果有的话）
                        if (StringUtils.hasText(userReportSaveReqVO.getName())) {
                            updateReqVO.setReportName(userReportSaveReqVO.getName());
                        }

                        // 设置用户填写的问题内容
                        if (StringUtils.hasText(userReportSaveReqVO.getQuestion())) {
                            updateReqVO.setQuestion(userReportSaveReqVO.getQuestion());
                        }

                        // 更新AnswerRecord
                        answerRecordService.updateAnswerRecord(updateReqVO);
                        log.info("[generateReport][已立即更新AnswerRecord: answerRecordId={}, reportName={}, question长度={}]",
                                userReportSaveReqVO.getAnswerRecordId(),
                                userReportSaveReqVO.getName(),
                                userReportSaveReqVO.getQuestion() != null ? userReportSaveReqVO.getQuestion().length() : 0);
                    }
                } catch (Exception e) {
                    log.warn("[generateReport][更新AnswerRecord失败: answerRecordId={}, reportName={}, question长度={}]",
                            userReportSaveReqVO.getAnswerRecordId(),
                            userReportSaveReqVO.getName(),
                            userReportSaveReqVO.getQuestion() != null ? userReportSaveReqVO.getQuestion().length() : 0, e);
                }
            }

            // 发送消息到队列进行异步处理
            reportProducer.sendReportGenerateMessage(
                    userReportSaveReqVO.getUserId(),
                    userReportSaveReqVO.getAnswerRecordId(),
                    userReportSaveReqVO.getQuestion(),
                    userReportSaveReqVO.getVersion(),
                    userReportSaveReqVO.getName()
            );

            log.info("[generateReport][报告生成请求已提交到队列: userId={}, answerRecordId={}]",
                    userReportSaveReqVO.getUserId(), userReportSaveReqVO.getAnswerRecordId());

            return success(true);
        } catch (Exception e) {
            log.error("[generateReport][报告生成请求提交失败: userId={}, answerRecordId={}]",
                    userReportSaveReqVO.getUserId(), userReportSaveReqVO.getAnswerRecordId(), e);
            throw new RuntimeException("报告生成请求提交失败", e);
        }
    }


    @PostMapping("/create")
    @Operation(summary = "创建AI 报告")
    @PermitAll
    public CommonResult<Long> createUserReport(@Valid @RequestBody UserReportSaveReqVO createReqVO) {
        return success(userReportService.createUserReport(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新AI 报告")
    @PermitAll
    public CommonResult<Boolean> updateUserReport(@Valid @RequestBody UserReportSaveReqVO updateReqVO) {
        userReportService.updateUserReport(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除AI 报告")
    @Parameter(name = "id", description = "编号", required = true)
    @PermitAll
    public CommonResult<Boolean> deleteUserReport(@RequestParam("id") Long id) {
        userReportService.deleteUserReport(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得AI 报告")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<UserReportRespVO> getUserReport(@RequestParam("id") Long id) {

        Long userId = getLoginUserId();
//        // 发送报告完成微信订阅消息
//        userReportService.sendReportCompletedMessage(userId, "222", 1,2622L);

        UserReportDO userReport = userReportService.getUserReport(id);
        if (userReport != null) {
            if(userReport.getContent()!=null) {
                userReport.setContent(BaiduAiUtils.mdConvertTHtml(userReport.getContent()));
            }
        }
        return success(BeanUtils.toBean(userReport, UserReportRespVO.class));
    }

    @PostMapping("/getReport")
    @Operation(summary = "获得AI 报告")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<List<UserReportDO>> getReport(@RequestBody UserReportSaveReqVO userReportSaveReqVO) {
        List<UserReportDO> userReport = userReportService.getUserReportByUserId(userReportSaveReqVO.getUserId(),userReportSaveReqVO.getAnswerRecordId());
        for (UserReportDO userReportDO : userReport) {
            if(userReportDO.getContent()!=null){
                userReportDO.setContent(BaiduAiUtils.mdConvertTHtml(userReportDO.getContent()));
            }
        }
        return success(userReport);
    }

    @GetMapping("/page")
    @Operation(summary = "获得AI 报告分页")
    @PermitAll
    public CommonResult<PageResult<UserReportRespVO>> getUserReportPage(@Valid UserReportPageReqVO pageReqVO) {
        PageResult<UserReportDO> pageResult = userReportService.getUserReportPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, UserReportRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出AI 报告 Excel")
    @PermitAll
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserReportExcel(@Valid UserReportPageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UserReportDO> list = userReportService.getUserReportPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "AI 报告.xls", "数据", UserReportRespVO.class,
                BeanUtils.toBean(list, UserReportRespVO.class));
    }


}
